<?php

class Campaigndetail extends Controller
{
	private  $_template_f;  
	function __construct()
	{
		parent::Controller();
		$this->_lang = $this->mycommon->getLangCode();
		$this->load->language('common', $this->_lang);
		$common_lang = $this->lang->line('common_lang');
		if(!$this->session->userdata('uname'))
		{
			redirect(site_url('login/'));
			die();
		}
		else
		{
			$permitid = $this->session->userdata('permitid');
			if(!is_numeric($permitid) || $permitid > -1)
			{
				show_error($common_lang['access_denied']);
				die();
			}
		}
		
		$this->_template_f = $this->config->item('template_f');
		$this->load->language('campaigndetail/campaigndetail', $this->_lang);
		$this->load->helper('breadcrumb');
        $this->load->model('campaigndetail/campaigndetail_model');	
        $this->load->library('mychart');
	}
	
	function _loadHeader($title = '')
	{
		$header = array();
		$header['title'] = $title == '' ? 'Self serving' : $title;
		$header['template_f'] = $this->_template_f;
		
		$header['username'] = '';
		$header['userid'] = '';
		$header['permitid'] = '';
        $header['module_name'] = 'campaigndetail';
		$header['lang'] = $this->_lang;
		$header['common_lang'] = $this->lang->line('common_lang');
		
		if($this->session->userdata('uname'))
		{
			$header['username'] = $this->session->userdata('uname');
			$header['userid'] = $this->session->userdata('uid');
			$header['permitid'] = $this->session->userdata('permitid');
		}
		
		// load header
		$this->load->view($this->_template_f . 'preheader_view');
		$this->load->view($this->_template_f . 'header_view', $header);
	}	
    
	function _loadMenu()
	{
		$data = array();
		$data['username'] = '';
		$data['userid'] = '';
		$data['permitid'] = '';
		$data['lang'] = $this->_lang;
		if($this->session->userdata('uname'))
		{
			$data['username'] = $this->session->userdata('uname');
			$data['userid'] = $this->session->userdata('uid');
			$data['permitid'] = $this->session->userdata('permitid');
		}
		$data['common_lang'] = $this->lang->line('common_lang');
        
		$this->load->view($this->_template_f . 'menu_view',$data);
	}
	
	function _loadFooter()
	{
		$this->load->view($this->_template_f . 'footer_view');
	}
	
    function index()
    {
        if(!$this->session->userdata('uname')){
			$currUrl = $this->mycommon->getCurrentUrl();
			redirect(site_url('/login'). '/?url=' . urlencode($currUrl));
			die();
		}
        $campaigndetail_lang = $this->lang->line('campaigndetail_lang');
        //variables
        $userid = $this->session->userdata('uid');
        $permitid = $this->session->userdata('permitid');
        $groupid = $this->session->userdata('groupid');
        $data['campaignid']=$campaignid=$this->input->get('campaignid');
        $data['todate']=$todate=$this->input->get('todate');
        $data['fromdate'] = $fromdate=$this->input->get('fromdate');
        
        $data['status']=$status =123;
        $data['status2']=$status2 =-1;
        $data['locationid'] = $locationid=-1;
        $data['location'] = $this->campaigndetail_model->selfserving_get_list_location();
        
        $data['page'] = $page = (is_numeric($this->input->get('page'))&&($this->input->get('page')>0)) ? $this->input->get('page'):1;
        $data['rownum'] = $rownum = (is_numeric($this->input->get('rownum'))&&($this->input->get('rownum')>0)) ? $this->input->get('rownum'): 20;
        $data['type'] = $type = (is_numeric($this->input->get('type'))&&($this->input->get('type')>0)) ? $this->input->get('type'):0;
        
        $lstBanner = $this->input->get('lstBanner') ? $this->input->get('lstBanner') :'';
        $data['temp']=array();
        $data['temp']= $this->input->get('lstBanner') ? explode(',',$lstBanner):array();
        //load data 1st table
        $data['campaignName']=$this->campaigndetail_model->selfservingGetAllCampaignInfo($campaignid);
        $data['userName']=$this->campaigndetail_model->selfserving_get_user_info($data['campaignName'][0]['uid']);
        $chkPermit = check_permit_id($userid,$permitid,$groupid,$campaignid,0);
        $chkFromDate = is_date($fromdate);
        $chkToDate   = is_date($todate);
        
        if(($chkPermit==false)||($chkFromDate==false)||($chkToDate==false)||($fromdate>$todate))
        {
            redirect(site_url('banner/error'));
            die();
        }else{
            //load header
            $this->_loadHeader($campaigndetail_lang['campaigndetail']);
            //load menu
            $this->_loadMenu();
            //load data 2nd table
            $lstBanner1= $this->campaigndetail_model->selfservingGetListbanners($campaignid);
            $data['lstBanner'] = $lstBanner1['allBanner'];
            $data['price']=$price = $this->config->item('cpc_price_vat');

            $banner = $this->campaigndetail_model->selfservingGetAllByCampaign($campaignid, $fromdate, $todate, $page, $rownum, $status, $locationid, $status2);
            
            $data['info']=$banner['banner'];
            $data['total']=$banner['total'];
            $data['totalpage']=$banner['totalpage'];
            $data['totalprice'] = $banner['totalprice'];
            
            $data['campaigndetail_lang'] = $campaigndetail_lang;
            $this->load->view($this->_template_f . 'campaigndetail/campaigndetail_view',$data);
            $this->_loadFooter();
        }
    }
	
    function ajax_chart()
    {
        if(!$this->session->userdata('uname'))
        {
			echo 'unlogin';
			die();
		}
        $data['campaignid'] = $campaignid = $this->input->get('campaignid');
        $data['fromdate'] = $fromdate = $this->input->get('fromdate');
        $data['todate'] =$todate = $this->input->get('todate');
        $userid = $this->session->userdata('uid');
        $permitid = $this->session->userdata('permitid');
        $groupid = $this->session->userdata('groupid');
        $chkPermit = check_permit_id($userid,$permitid,$groupid,$campaignid,0);
        $chkFromDate = is_date($fromdate);
        $chkToDate   = is_date($todate);
        if(($chkPermit==false)||($chkFromDate==false)||($chkToDate==false))
        {
            echo 'error';
			die();
        }
        $type = ($this->input->get('type') != 0)&&($this->input->get('type') != 1) ? 0 : $this->input->get('type');
        $lstBanner = $this->input->get('lstBanner') ? $this->input->get('lstBanner'):'';
        if($lstBanner!='')
        {
            if(check_permit_id($userid,$permitid,$groupid,$lstBanner,1)==false)
            {
                echo 'error';
                die();    
            }
        }
        $temp= explode(",", $lstBanner);
        if($lstBanner!='')
        {
            foreach($temp as $t)
            {
                $ok = check_permit_id($userid,$permitid,$groupid,$t,1);
            }
            if($ok==false)
            {
                echo 'error';
    			die();
            }
        }
        $data = $this->chart_data($campaignid,$fromdate,$todate,$type,$lstBanner);
        $this->load->view($this->_template_f . 'campaign/chart_view',$data);
    }
    
    function edit()
    {
        $val = $this->input->post('ns');
        $bannerid = $this->input->get('bannerid');
        $type = $this->input->get('type');
        if($val==4)
        {
            //restore
            $type=4;
            $val=0;
        }elseif($val==3)
        {
            //deleted
            $type=4;
            $val=1;
        }
        $this->load->model('banner/banner_model');
        $count = $this->banner_model->selfserving_banner_update_inline($bannerid,$val,$type);
        if($count==true)
        {
            if($type==1 && $val=='1'){
                echo '<img class="cursor-pointer" alt="" src="/images/imgrun.gif"/>';
            }elseif($type==1 && $val=='2')
            {
                echo '<img class="cursor-pointer" alt="" src="/images/imgpause.gif"/>';
            }elseif($type==4 && $val=='1')
            {
                echo '<img class="cursor-pointer" alt="" src="/images/temp_deleted.gif"/>';
                echo '<script type="text/javascript">window.location.reload();</script>';
            }elseif($type==4 && $val=='0')
            {
                echo '<img class="cursor-pointer" alt="" src="/images/temp_deleted.gif"/>';
                echo '<script type="text/javascript">window.location.reload();</script>';
            }else{
                echo $val;
            }
        }else{
            echo 'Error,try again,please!';
        }      
    }
    function editCampaign()
    {
        $val = $this->input->post('ns');
        $campaignid = $this->input->get('campaignid');
        $type = $this->input->get('type');
        $userid = $this->session->userdata('uid');
        $count = $this->campaigndetail_model->selfserving_campaign_update_inline($campaignid,$val,$type,$userid);
        if($count==true)
        {
            if($type==1 && $val=='1'){
                echo '<img class="cursor-pointer" alt="" src="/images/imgrun.gif"/> Đang chạy';
            }elseif($type==1 && $val=='5')
            {
                echo '<img class="cursor-pointer" alt="" src="/images/imgpause.gif"/> Tạm dừng';
            }elseif($type==1 && $val=='-1')
            {
                echo '<img class="cursor-pointer" alt="" src="/images/imgok.gif"/> Hoàn thành';
            }else{
                echo $val;
            }
        }else{
            echo 'Error,try again,please!';
        }
    }
    
    function editDuration()
    {
        $campaignid = $this->input->get('campaignid');
        $fromdate = $this->input->get('fromdate');
        $todate = $this->input->get('todate');
        $data['campaigndetail_lang']=$this->lang->line('campaigndetail_lang');
        $curvalue=$this->campaigndetail_model->selfserving_get_current_value_of_campaign($campaignid,2);
        $strDuration=$fromdate.','.$todate.','.$curvalue[0];
        $userid = $this->session->userdata('uid');
        $count = $this->campaigndetail_model->selfserving_campaign_update_inline($campaignid,$strDuration,4,$userid);
        if($count==true)
        {
            $fromdate = date('d/m/Y',strtotime($fromdate));
            $todate = date('d/m/Y',strtotime($todate));
            if($todate=='31/12/2035')
            {
                echo 'Chiến dịch chạy liên tục từ ngày '.$fromdate;
            }
            else{
                echo $str = $fromdate.' '.$data['campaigndetail_lang']['to'].' '.$todate;
            }
        }else{
            echo 'Error,try again,please!';
        }
    }
    function editBudget()
    {
        $campaignid = $this->input->get('campaignid');
        $type = $this->input->get('type');
        $userid = $this->session->userdata('uid');
        $val = $this->input->get('value');

        $bytype = $this->input->get('byType');

        $fromdate = date('Y/m/d',strtotime($this->input->get('fromdate')));
        $todate = date('Y/m/d',strtotime($this->input->get('todate')));
        $count= count($this->mychart->createDateRangeArray($fromdate,$todate));
        
        if($bytype==0)
        {
            $curvalue=$this->campaigndetail_model->selfserving_get_current_value_of_campaign($campaignid,3);
        }else{
            $curvalue=$this->campaigndetail_model->selfserving_get_current_value_of_campaign($campaignid,1);
        }
        if($val<$curvalue[0])
        {
            $campaigndetail_lang = $this->lang->line('campaigndetail_lang');
            $campaignName=$this->campaigndetail_model->selfservingGetAllCampaignInfo($campaignid);
            echo '<script type="text/javascript">alert(\'Ngân sách phải lớn hơn '.$curvalue[0].'\');</script>';
            if($campaignName[0]['isperday']==1)
            {
                echo '<div id="divBudget">
                    <span id="editBudget">'.number_format($campaignName[0]['maxValueDay']).'(VND)</span>									
                    <a style="cursor:pointer;" class="mbd-edit ver-middle" id="edittriggerBudget">'.$campaigndetail_lang['edit'].'</a>
                    <p class="text-999">'.$campaigndetail_lang['byDate'].'</p>
                </div>';
            }else{
                echo '<div id="divBudget">
                    <span id="editBudget">'.number_format($campaignName[0]['ExpireValue']).'(VND)</span>									
                    <a style="cursor:pointer;" class="mbd-edit ver-middle" id="edittriggerBudget">'.$campaigndetail_lang['edit'].'</a>
                    <p class="text-999">'.$campaigndetail_lang['byCam'].'</p>
                </div>';
            }
        }else{
            $curvalue2=$this->campaigndetail_model->selfserving_get_current_value_of_campaign($campaignid,2);
            $str=$val.','.$bytype.','.$curvalue2['0'];
            $count = $this->campaigndetail_model->selfserving_campaign_update_inline($campaignid,$str,$type,$userid);
            if($count==true)
            {
                $campaigndetail_lang=$this->lang->line('campaigndetail_lang');
                $campaignName=$this->campaigndetail_model->selfservingGetAllCampaignInfo($campaignid);
                if($campaignName[0]['isperday']==1)
                {
                    echo '<span id="editBudget">'.number_format($campaignName[0]['maxValueDay']).'(VND)</span>									
                    <a style="cursor:pointer;" class="mbd-edit ver-middle" id="edittriggerBudget">'.$campaigndetail_lang['edit'].'</a>
                    <p class="text-999">'.$campaigndetail_lang['byDate'].'</p>';
                }else{
                    echo '<span id="editBudget">'.number_format($campaignName[0]['ExpireValue']).'(VND)</span>									
                    <a style="cursor:pointer;" class="mbd-edit ver-middle" id="edittriggerBudget">'.$campaigndetail_lang['edit'].'</a>
                    <p class="text-999">'.$campaigndetail_lang['byCam'].'</p>';
                }
            }else{
                echo 'Error,try again,please!';
            }
        }
    }
    function chart_data($campaignid,$fromdate,$todate,$type,$lstBanner)
    {
		$this->mychart->createDataHour($fromdate,array());
		$arrDate=$this->mychart->createDateRangeArray($fromdate,$todate);
		$fromTime=mktime(0,0,0,substr($fromdate,5,2),substr($fromdate,8,2),substr($fromdate,0,4));
		$toTime=mktime(0,0,0,substr($todate,5,2),substr($todate,8,2),substr($todate,0,4));
        $data=array();
        $campaigndetail_lang = $this->lang->line('campaigndetail_lang');
        $userid = $this->session->userdata('uid');
        if($fromdate != $todate)
        {
            if($lstBanner=='')
            {
                $chartdata = $this->campaigndetail_model->selfservingGetAllCampaignChart($fromdate, $todate, $campaignid, $type);
				$arrData=$this->mychart->createData($arrDate,$fromdate,$chartdata['cam1']);
                $label1 = $campaigndetail_lang['campaign'].':'.$chartdata['cam2'][0]['campaignname'];
                $data['type'] = ($type==0)?'Click':$campaigndetail_lang['impressions'];
                $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData,'color'=>'#627AAD'));
                $data['date']=json_encode($arrDate);
                $data['step'] =(count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
                return $data;
            }else{
                $lstBannerCount = explode(',',$lstBanner);
                if(count($lstBannerCount)==1)
                {
                    $chartdata = $this->campaigndetail_model->selfservingGetBannerChart($lstBannerCount[0],$fromdate,$todate,$type);
                    $data1=$temp1=array();
                    $arrData=$this->mychart->createData($arrDate,$fromdate,$chartdata['banner']);
                    $data['type']= ($type==0)?'Click':$campaigndetail_lang['impressions'];
                    $label1=$chartdata['ban'][0]['bannername'];
                    $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData,'color'=>'#627AAD'));
                    $data['date']=json_encode($arrDate);
                    $data['step'] =(count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
                    return $data;
                }else{
                    $chartdata = $this->campaigndetail_model->selfservingGetBannerChart($lstBanner,$fromdate,$todate,$type);
                    $arrData=$this->mychart->createData($arrDate,$fromdate,$chartdata['banner'],$lstBannerCount);
                    if($chartdata['ban'][0]['bannerid']==$lstBannerCount[0])
                    {
                        $label1=$chartdata['ban'][0]['bannername'];
                        $label2=$chartdata['ban'][1]['bannername'];
                    }else{
                        $label1=$chartdata['ban'][1]['bannername'];
                        $label2=$chartdata['ban'][0]['bannername'];
                    }
                    $data['type'] = ($type==0)?'Click':$campaigndetail_lang['impressions'];
                    $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData['data1'],'color'=>'#627AAD'));
                    $data['data1']=json_encode(array('name'=>strip_tags($label2),'data'=>$arrData['data2'],'color'=>'#FF9900'));
                    $data['date']=json_encode($arrDate);
                    $data['step'] =(count($arrDate)<=10)?1:((count($arrDate)<=14)?2:floor(count($arrDate)/7));
                    return $data;
                }
            }
        }else{
            $lstBannerCount =($lstBanner=='')?array(): explode(',',$lstBanner);
            $countBanner=count($lstBannerCount);
            $curdate=$todate;
            if($lstBanner=='' || $countBanner==1)
            {   
                if($countBanner==1){
                   $chartdata = $this->campaigndetail_model->selfserving_get_banner_chart_hour($lstBanner,$curdate,$type);
                   $arrData=$this->mychart->createDataHour($curdate,$chartdata['bannerinfo']);                   
                }
                else{
                    $chartdata = $this->campaigndetail_model->selfserving_get_campaign_chart_hour($campaignid,$curdate,$type,$userid);
                   $arrData=$this->mychart->createDataHour($curdate,$chartdata['campaigninfo']); 
                }
                $label1=($countBanner==1)? $chartdata['bannername'][0]['bannername']:'Chiến dịch:'.$chartdata['campaignname'][0]['campaignname'];
                $data['type'] = ($type==0)? 'Clicks':$campaigndetail_lang['impressions'];
                $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData['data'],'color'=>'#627AAD'));
                $data['date']=json_encode($arrData['hour']);
                return $data;
            }else{
                $chartdata = $this->campaigndetail_model->selfserving_get_banner_chart_hour($lstBanner,$curdate,$type);
                $arrData=$this->mychart->createDataHour($curdate,$chartdata['bannerinfo'],$lstBannerCount);
                if($chartdata['bannername'][0]['bannerid']==$lstBannerCount[0])
                {
                    $label1=$chartdata['bannername'][0]['bannername'];
                    $label2=$chartdata['bannername'][1]['bannername'];
                }else{
                    $label1=$chartdata['bannername'][1]['bannername'];
                    $label2=$chartdata['bannername'][0]['bannername'];
                }
                $data['type'] = ($type==0)?'Click':$campaigndetail_lang['impressions'];
                $data['data']=json_encode(array('name'=>strip_tags($label1),'data'=>$arrData['data1'],'color'=>'#627AAD'));
                $data['data1']=json_encode(array('name'=>strip_tags($label2),'data'=>$arrData['data2'],'color'=>'#FF9900'));
                $data['date']=json_encode($arrData['hour']);
                return $data;
            }
        }
    }
}
?>